package ml.kupin.order.interceptor;

import com.alibaba.fastjson.JSON;
import ml.kupin.cart.service.CartService;
import ml.kupin.common.constant.KuPinConstant;
import ml.kupin.common.utils.CookieUtils;
import ml.kupin.common.utils.KuPinResult;
import ml.kupin.pojo.TbItem;
import ml.kupin.pojo.TbUser;
import ml.kupin.sso.service.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录状态拦截器，判断用户是否登陆，
 * 如果已登录，将用户信息放入request域中，方便controller取用。
 * 如果未登录，重定向到登录页面。
 * <p>
 * Created by 小柯(Allen Kerr) on 17.5.8 18:56.
 */
public class UserLoginStatusInterceptor4Order implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private CartService cartService;

    @Value("${token_cookie_name}")
    private String token_cookie_name;
    @Value("${sso_web_url}")
    private String sso_web_url;
    @Value("${cart_cookie_name}")
    private String cart_cookie_name;

    //前处理，执行handler之前执行此方法。
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie中取token
        String token = CookieUtils.getCookieValue(request, token_cookie_name);
        //判断
        if (StringUtils.isNotBlank(token)) {
            //cookie中有token信息
            KuPinResult kuPinResult = tokenService.getUserByTokenFromRedis(token);
            if (kuPinResult.getStatus() == KuPinConstant.KuPinResult_status_success) {
                //用户为登录状态
                TbUser user = (TbUser) kuPinResult.getData();
                request.setAttribute("user", user);
                //判断cookie中是否有购物车数据，如果有就合并到服务端。
                /**
                 * 注意，购物车列表项在加入cookie的时候，json字符串是使用utf-8编码的！
                 */
                //String json_cartItemList = CookieUtils.getCookieValue(request, cart_cookie_name);这么写会报错！
                String json_cartItemList = CookieUtils.getCookieValue(request, cart_cookie_name, true);
                if (StringUtils.isNotBlank(json_cartItemList)) {
                    //合并购物车
                    cartService.mergeCart(user.getId(), JSON.parseArray(json_cartItemList, TbItem.class));
                }
                //放行
                return true;
            }
        }
        //用户未登录，拦截，重定向到登录页面
        //登录成功后，再跳转回来
        response.sendRedirect(sso_web_url + "/user/login?redirect=" + request.getRequestURL());
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
